<!--src/views/aichat/Dept.vue-->
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useAuthStore } from '@/stores/modules/authStore.js'
import { getLegalAdvice } from '@/views/AiChat/legalAdvice.js'
import '@/styles/aichat.css'

const authStore = useAuthStore()
const messages = ref([])
const newMessage = ref('')
const isLoading = ref(false)
const errorMessage = ref('')
const copyStatus = ref(null)
let copyStatusTimer = null
const messagesContainer = ref(null)

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 获取用户特定的存储键
const getStorageKey = () => {
  return `ai_chat_${authStore.userInfo?.username || 'anonymous'}_messages`
}

// 加载存储的消息
const loadMessages = () => {
  try {
    const savedMessages = localStorage.getItem(getStorageKey())
    if (savedMessages) {
      messages.value = JSON.parse(savedMessages)
    } else {
      addAIMessage('您好！我是专业法律AI顾问，请提出您的法律问题。')
    }
  } catch (error) {
    console.error('加载聊天记录失败:', error)
    addAIMessage('您好！我是专业法律AI顾问，请提出您的法律问题。')
  }
  scrollToBottom()
}

// 保存消息到本地存储
const saveMessages = () => {
  try {
    localStorage.setItem(getStorageKey(), JSON.stringify(messages.value))
  } catch (error) {
    console.error('保存聊天记录失败:', error)
  }
}

// 清空当前聊天记录
const clearChatHistory = () => {
  if (confirm('确定要清空当前聊天记录吗？')) {
    messages.value = []
    localStorage.removeItem(getStorageKey())
    addAIMessage('您好！我是专业法律AI顾问，请提出您的法律问题。')
  }
}

// 复制文本到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    showCopyStatus('复制成功', 'success')
  } catch (err) {
    console.error('复制失败:', err)
    try {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      const success = document.execCommand('copy')
      document.body.removeChild(textarea)
      if (success) {
        showCopyStatus('复制成功', 'success')
      } else {
        showCopyStatus('复制失败，请手动复制', 'error')
      }
    } catch (e) {
      showCopyStatus('复制失败，请手动复制', 'error')
    }
  }
}

// 显示复制状态
const showCopyStatus = (message, type) => {
  copyStatus.value = { message, type }

  if (copyStatusTimer) {
    clearTimeout(copyStatusTimer)
  }

  copyStatusTimer = setTimeout(() => {
    copyStatus.value = null
  }, 2000)
}

// 初始化时加载消息
onMounted(loadMessages)

// 监听消息变化并保存
watch(messages, () => {
  saveMessages()
  scrollToBottom()
}, { deep: true })

const addAIMessage = (text) => {
  const newMsg = {
    text,
    sender: 'ai',
    timestamp: new Date().toISOString(),
    isFormatted: isFormattedResponse(text)
  }
  messages.value.push(newMsg)
  return newMsg
}

const addUserMessage = (text) => {
  const newMsg = {
    text,
    sender: 'user',
    timestamp: new Date().toISOString(),
    isFormatted: false
  }
  messages.value.push(newMsg)
  return newMsg
}

// 判断是否为格式化响应
const isFormattedResponse = (text) => {
  return text.includes('###') || text.includes('|') || text.includes('---')
}

// 格式化AI响应文本
const formatResponse = (text) => {
  if (!isFormattedResponse(text)) return text

  // 处理Markdown格式
  let formattedText = text
      .replace(/### (.*?)\n/g, '<h3>$1</h3>')
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      .replace(/`(.*?)`/g, '<code>$1</code>')
      .replace(/---/g, '<hr>')

  // 处理表格
  if (text.includes('|')) {
    formattedText = formattedText.replace(
        /(\|.*?\|\n\|.*?\|\n)((?:\|.*?\|\n)+)/g,
        (match, header, body) => {
          const headers = header.split('|').filter(Boolean).map(h => h.trim())
          const rows = body.split('\n').filter(Boolean)

          let tableHtml = '<div class="legal-table"><table>'
          tableHtml += '<thead><tr>'
          headers.forEach(h => {
            tableHtml += `<th>${h}</th>`
          })
          tableHtml += '</tr></thead><tbody>'

          rows.forEach(row => {
            const cells = row.split('|').filter(Boolean).map(c => c.trim())
            tableHtml += '<tr>'
            cells.forEach(c => {
              tableHtml += `<td>${c}</td>`
            })
            tableHtml += '</tr>'
          })

          tableHtml += '</tbody></table></div>'
          return tableHtml
        }
    )
  }

  // 处理列表
  formattedText = formattedText.replace(
      /(\d+\.\s.*?)(?=\n\d+\.|\n\n|$)/g,
      '<li>$1</li>'
  )

  return formattedText
}

const sendMessage = async () => {
  const message = newMessage.value.trim()
  if (!message) return

  const userMessage = addUserMessage(message)
  newMessage.value = ''
  isLoading.value = true
  errorMessage.value = ''

  try {
    const recentMessages = messages.value.slice(-10)
    const aiResponse = await getLegalAdvice(message, recentMessages)
    addAIMessage(aiResponse)
  } catch (error) {
    console.error('获取法律建议失败:', error)
    errorMessage.value = '法律咨询服务暂时不可用'

    const defaultResponses = {
      admin: '系统提示：服务维护中，请检查API配置。',
      lawyer: '系统提示：服务暂时不可用。建议查阅《最高人民法院指导案例》或《法律适用》。',
      public: '系统提示：当前服务不可用。您可拨打12348法律援助热线或前往当地司法局咨询。'
    }

    addAIMessage(defaultResponses[authStore.userInfo?.role || 'public'])
  } finally {
    isLoading.value = false
  }
}

const handleKeyPress = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}
</script>

<template>
  <main class="page-container">
    <div class="chat-header">
      <div class="header-content">
        <h3>AI法律咨询</h3>
        <button @click="clearChatHistory" class="clear-btn">
          <i class="icon-trash"></i> 清空记录
        </button>
      </div>
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>

    <div class="chat-container">
      <div class="messages" ref="messagesContainer">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.sender]"
        >
          <div class="avatar">
            <span v-if="message.sender === 'ai'">AI</span>
            <span v-else>我</span>
          </div>
          <div class="message-content">
            <div
                class="message-text"
                v-if="message.isFormatted"
                v-html="formatResponse(message.text)"
            ></div>
            <div
                class="message-text"
                v-else
            >{{ message.text }}</div>
            <div class="message-footer">
              <span class="message-time">
                {{ new Date(message.timestamp).toLocaleTimeString() }}
              </span>
              <button class="copy-btn" title="复制内容" @click="copyToClipboard(message.text)">
                <i class="icon-copy"></i>
              </button>
            </div>
          </div>
        </div>

        <div v-if="isLoading" class="message ai">
          <div class="avatar">AI</div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <div class="input-container">
        <div class="disclaimer">
          <i class="icon-info"></i>
          <span>AI生成内容仅供参考，请仔细甄别</span>
        </div>
        <div class="input-area">
          <textarea
              v-model="newMessage"
              @keydown="handleKeyPress"
              placeholder="输入您的法律问题..."
              rows="2"
          ></textarea>
          <button
              @click="sendMessage"
              :disabled="isLoading || !newMessage.trim()"
              class="send-button"
          >
            <i class="icon-send"></i>
          </button>
        </div>
      </div>
    </div>

    <transition name="fade">
      <div v-if="copyStatus" :class="['copy-status', copyStatus.type]">
        {{ copyStatus.message }}
      </div>
    </transition>
  </main>
</template>


<style scoped>
.page-container {
  padding: 10px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  position: relative;
}

.chat-header {
  margin-bottom: 15px;
  padding-bottom: 0;
  border-bottom: 1px solid #eaeaea;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1px;
  weight:60%
}

.clear-btn {
  background: #ffa2a2;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 0.8rem;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}



.error-message {
  color: #f56c6c;
  font-size: 0.9rem;
}



.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #eeeeee;
  scroll-behavior: smooth;
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: bold;
  flex-shrink: 0;
}

.message.ai .avatar {
  background-color: #67c23a;
}

.message-content {
  max-width: 80%;
  min-width: 200px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  font-size: 0.95rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message.user .message-text {
  background: #409eff;
  color: white;
  border-top-right-radius: 4px;
}

.message.ai .message-text {
  background: white;
  color: #333;
  border: 1px solid #eaeaea;
  border-top-left-radius: 4px;
}

.message-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 6px;
  gap: 8px;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}

.copy-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 2px;
  opacity: 0;
  transition: all 0.2s;
}

.message:hover .copy-btn {
  opacity: 1;
}

.copy-btn:hover {
  color: #409eff;
}

.typing-indicator {
  display: flex;
  gap: 6px;
  padding: 12px 16px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #999;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

.input-container {
  padding: 10px;
  border-top: 1px solid #bddaff;
  background: white;
  height: 20%;
}
.disclaimer {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.8rem;
  color: #999;
  margin-bottom: 3px;
}

.input-area {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

textarea {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  resize: none;
  font-family: inherit;
  font-size: 0.95rem;
  min-height: 60px;
  max-height: 120px;
  transition: border-color 0.2s;
}

textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.send-button {
  width: 52px;
  height: 61px;
  border-radius: 42%;
  background: #409eff;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.send-button:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.send-button:not(:disabled):hover {
  background: #66b1ff;
  transform: scale(1.05);
}

/* 图标样式 */
[class^="icon-"] {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-refresh {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='23 4 23 10 17 10'%3E%3C/polyline%3E%3Cpolyline points='1 20 1 14 7 14'%3E%3C/polyline%3E%3Cpath d='M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15'%3E%3C/path%3E%3C/svg%3E");
}

.icon-copy {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='9' y='9' width='13' height='13' rx='2' ry='2'%3E%3C/rect%3E%3Cpath d='M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1'%3E%3C/path%3E%3C/svg%3E");
}

.icon-send {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='22' y1='2' x2='11' y2='13'%3E%3C/line%3E%3Cpolygon points='22 2 15 22 11 13 2 9 22 2'%3E%3C/polygon%3E%3C/svg%3E");
}

.icon-info {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='16' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='8' x2='12.01' y2='8'%3E%3C/line%3E%3C/svg%3E");
}


/* 新增垃圾桶图标样式 */
.icon-trash {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='3 6 5 6 21 6'%3E%3C/polyline%3E%3Cpath d='M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'%3E%3C/path%3E%3Cline x1='10' y1='11' x2='10' y2='17'%3E%3C/line%3E%3Cline x1='14' y1='11' x2='14' y2='17'%3E%3C/line%3E%3C/svg%3E");
}

.clear-btn:hover {
  background: #f5f7fa;
}

.copy-status {
  position: fixed;
  top:80px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 24px;
  border-radius: 4px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  animation: slide-up 0.3s ease-out;
}

.copy-status.success {
  background-color: #4CAF50;
  color: white;

}

.copy-status.error {
  background-color: #f44336;
  color: white;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

@keyframes slide-up {
  from {
    opacity: 0;
    transform: translate(-50%, 20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}
</style>